package com.cdream.basic.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * @author cdream
 * @date 2022/10/21
 */
@Slf4j
public class HelloServer {
    public static void main(String[] args) {
        DefaultEventLoopGroup group = new DefaultEventLoopGroup();
        // 启动器，负责组装netty组件，启动服务
        new ServerBootstrap()
                // selector + thread，事件监听，分发处理
                .group(new NioEventLoopGroup(), new NioEventLoopGroup(2))
                // 服务器SSC的实现
                .channel(NioServerSocketChannel.class)
                // boss处理连接，worker（child）处理读写,决定worker可以执行哪些操作
                .childHandler(
                        // 和客户端连接后读写的通道
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                // 将byteBuf转为字符串
                                // ch.pipeline().addLast(new StringDecoder());
                                // 自定义handler
                                ch.pipeline().addLast("handler1", new ChannelInboundHandlerAdapter() {
                                    // 触发读事件的时候执行的消息
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

                                        log.info(((ByteBuf) msg).toString(StandardCharsets.UTF_8));
                                        ctx.fireChannelRead(msg);
                                    }
                                }).addLast(group, "handler2", new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.info(((ByteBuf) msg).toString(StandardCharsets.UTF_8));
                                        ctx.writeAndFlush(msg);
                                    }
                                });
                            }
                        })
                .bind(9011);

    }
}
